import config from './config'
import { postToken } from '@/api/app'
import { setToken } from '@/utils/auth'
import store from '@/store'
const {
  USERNAME,
  PASSWORD,
  USERTYPE
} = config

/* 判断是否有jsbridge*/
const readyApi = callback => {
  if (window.AlipayJSBridge) {
    callback && callback()
  } else {
    document.addEventListener('AlipayJSBridgeReady', callback, false)
  }
}

/* 检查Token*/
export const checkToken = () => {
  return new Promise((resolve, reject) => {
    /* 开发环境和生产环境的判断*/
    if (process.env.NODE_ENV === 'development') {
      postToken({
        username: USERNAME,
        password: PASSWORD,
        userType: USERTYPE
      }).then(res => {
        setToken(res.data.access_token || '')
        resolve(1)
      }).catch(() => {
        reject(0)
      })
    } else {
      readyApi(() => {
        window.AlipayJSBridge.call('hideTitlebar')
        window.AlipayJSBridge.call('getToken', {}, res => {
          if (res.code === 200 || res.code === 10000) {
            setToken(res.data.access_token || '')
            resolve(1)
          } else {
            reject(0)
          }
        })
      })
    }
  })
}

/* 获取用户名称和编码放到水印文字中*/
export const getWaterMarkText = () => {
  return new Promise((resolve, reject) => {
    if (process.env.NODE_ENV === 'development') {
      resolve('')
    } else {
      window.AlipayJSBridge.call('getHWUserDefault', {}, res => {
        resolve(res.userName + '-' + res.userCode || '')
      }, () => {
        resolve('')
      })
    }
  })
}

/* 检测如果是从其他app跳转，将参数放到store中*/
export const judgeObserver = (to) => {
  return new Promise(resolve => {
    if (to.query.headerUserCode) {
      store.commit('index/SET_HEADER_USER_CODE', to.query.headerUserCode)
      resolve()
    } else {
      resolve()
    }
  })
}

/**
 * 返回OSS上传所需信息
 */
 export function ossQuery () {
  const options = {
    policy: 'ZXlKbGVIQnBjbUYwYVc5dUlqb2lNakF6TUMwd01TMHdNVlF4TWpvd01Eb3dNQzR3TURCYUlpd2lZMjl1WkdsMGFXOXVjeUk2VzFzaVkyOXVkR1Z1ZEMxc1pXNW5kR2d0Y21GdVoyVWlMREFzTVRBME9EVTNOakF3TUYxZGZRPT0=',
    OSSAccessKeyId: 'TFRBSU9adHZpQkE5NEJXaQ==',
    signature: 'V3lyc3c3cTJ1TGtQaGNFN2t0NzVZV2tOVjFvPQ=='
  };
  const optionsTarget = {};
  for (const key in options) {
    optionsTarget[key] = atob(options[key]);
  }
  return optionsTarget;
}